// /common/websocket.js
let socket = null;

export function connectWebSocket(url, onMessage) {
  if (socket) {
    console.log('🔄 检测到旧连接，强制关闭');
    socket.close();
    socket = null;
  }

  socket = uni.connectSocket({
    url,
    success() {
      console.log('✅ WebSocket 连接成功');
    },
    fail(err) {
      console.error('❌ WebSocket 连接失败', err);
    }
  });

  socket.onOpen(() => {
    console.log('✅ WebSocket 已打开');
  });

  socket.onMessage((res) => {
    console.log('📩 收到推送：', res.data);
    onMessage && onMessage(res.data);
  });

  socket.onClose(() => {
    console.log('🔒 WebSocket 已关闭');
    socket = null;
  });

  return socket;
}

export function closeWebSocket() {
  if (socket) {
    socket.close();
    socket = null;
    console.log('👋 主动关闭 WebSocket 连接');
  } else {
    console.log('⚠️ 没有活跃的 WebSocket 连接');
  }
}

export function getWebSocket() {
  return socket;
}
